package com.ddxcloud.movie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddxcloud.common.handler.BusinessException;
import com.ddxcloud.common.utils.SignUtil;
import com.ddxcloud.movie.config.common.JwtProperties;
import com.ddxcloud.movie.data.constants.ActivityTypeConstant;
import com.ddxcloud.movie.data.constants.CouponStatusConstant;
import com.ddxcloud.movie.data.dto.CreateCodeDTO;
import com.ddxcloud.movie.data.entity.Activity;
import com.ddxcloud.movie.data.entity.Channel;
import com.ddxcloud.movie.data.entity.User;
import com.ddxcloud.movie.data.entity.UserCoupon;
import com.ddxcloud.movie.mapper.ActivityMapper;
import com.ddxcloud.movie.mapper.UserCouponMapper;
import com.ddxcloud.movie.service.ActivityService;
import com.ddxcloud.movie.service.ChannelService;
import com.ddxcloud.movie.service.CouponsService;
import com.ddxcloud.movie.service.UserService;
import com.ddxcloud.movie.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements ActivityService {

    @Resource
    ActivityMapper activityMapper;

    @Resource
    UserCouponMapper userCouponMapper;

    @Resource
    CouponsService couponsService;

    @Resource
    ChannelService channelService;

    @Resource
    UserService userService;

    @Resource
    JwtProperties jwtProperties;

    private static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return Objects.requireNonNull(attributes).getRequest();
    }

    @Override
    public List<Activity> getActivityByType(Integer activityType) {
        Channel channel = channelService.getById(getRequest().getHeader("channelId"));
        List<Activity> activities = activityMapper.getActivityByType(activityType, channel.getChannelId());
        if (!activities.isEmpty()) {
            Date nowDate = new Date();
            Iterator<Activity> iterator = activities.iterator();
            while (iterator.hasNext()) {
                Activity activity = iterator.next();
                Date startDate = activity.getStartTime();
                Date endDate = activity.getEndTime();
                if (nowDate.getTime() >= startDate.getTime() && nowDate.getTime() <= endDate.getTime()) {
                    log.info("可参与活动：{}", activity.getActivityName());
                } else {
                    iterator.remove();
                }
            }
        }
        return activities;
    }

    @Override
    public Boolean handleActivityToUser(Integer activityId) {
        Channel channel = channelService.getById(getRequest().getHeader("channelId"));
        Activity activity = this.getById(activityId);
        if (null != activity) {
            if (Objects.equals(activity.getActivityType(), ActivityTypeConstant.TYPE_0)) {
                Long couponId = Long.valueOf(activity.getAttach()); // 派送的优惠券ID
                Jws<Claims> claimsJws = JwtUtil.parseJWT(getRequest().getHeader(jwtProperties.getTokenName()));
                User user = userService.getById(Long.valueOf(claimsJws.getPayload().get("userId").toString()));
                if (null == user) {
                    throw new BusinessException("请先登录");
                }
                // 判断是否已经领取
                Integer isExist = userCouponMapper.isExistUserCouponByUserIdAndCouponId(user.getUserId(), couponId);
                if (isExist == null) {
                    CreateCodeDTO dto = new CreateCodeDTO();
                    dto.setCouponId(couponId);
                    dto.setSign(SignUtil.getSign(BeanUtil.beanToMap(dto), channel.getChannelSecret()));
                    JSONObject res = couponsService.createCode(dto);
                    if (res.containsKey("code") && res.getInteger("code") == 0) {
                        res = res.getJSONObject("data");
                        UserCoupon userCoupon = new UserCoupon();
                        userCoupon.setChannelId(channel.getChannelId());
                        userCoupon.setUserId(user.getUserId());
                        userCoupon.setCouponId(couponId);
                        userCoupon.setCouponTitle(res.getString("couponName"));
                        userCoupon.setCouponCode(res.getString("couponCode"));
                        userCoupon.setCouponInfo(res.toString());
                        userCoupon.setCouponStatus(CouponStatusConstant.STATUS_0); // 未使用
                        userCoupon.setCreateTime(res.getString("createTime"));
                        userCouponMapper.insert(userCoupon);
                        log.info("[{}] 参与活动: {} 参与人: {}", channel.getChannelName(), activity.getActivityName(), user.getUsername());
                    }
                } else {
                    throw new BusinessException("您已参与过活动，请勿重复参与");
                }
            }
        }
        return Boolean.TRUE;
    }
}
